package com.mini.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author zhangxiaobin
 * @title: AliOSSService
 * @description: TODO
 * @date 2019/11/1116:34
 */
@Slf4j
@Service
public class AliOSSService {

    @Autowired
    private OSSClient ossClient;

    @Value("${ali.oss.mini.domain}")
    private String miniDomain;

    @Value("${ali.oss.mini.bucket.name}")
    private String miniBucketName;

    @Value("${ali.test.states}")
    private String testStates;

    public String uploadImg(MultipartFile file,String path){
        String imgUrl = "";
        try {
            // 获取图片后缀名
            String resultSuffix = "";
            String originalFileName = file.getOriginalFilename();
            if (!StringUtils.isBlank(originalFileName)) {
                int start = originalFileName.lastIndexOf(".");
                start = start == -1 ? 0 : start;
                String suffix = originalFileName.substring(start, originalFileName.length());
                resultSuffix = suffix.startsWith(".") ? suffix : "." + suffix;
            }
            resultSuffix = StringUtils.isBlank(resultSuffix) ? ".jpg" : resultSuffix;
            if(".jpeg".equalsIgnoreCase(resultSuffix)){
                resultSuffix = ".jpg";
            }

            String newName = System.currentTimeMillis()+ resultSuffix;
            if("test".equalsIgnoreCase(testStates)){
                path = "test/" + path;
            }
            String localUploadFilePath =  path + newName;
            //上传到ali oss
            InputStream inputStream = file.getInputStream();

            ossClient.putObject(miniBucketName,localUploadFilePath,inputStream);

            imgUrl = miniDomain + "/" + localUploadFilePath ;

        } catch (Exception e) {
            log.error("上传图片报错，path = {} , e = {}", path , e);
        }
        return imgUrl;
    }


    public String uploadContent2OSS(String content,String localUploadFilePath,String domain){
        String imgUrl = "";
        try {

            if("test".equalsIgnoreCase(testStates)){
                localUploadFilePath = "test/" + localUploadFilePath;
            }

            PutObjectRequest putObjectRequest = new PutObjectRequest(miniBucketName,localUploadFilePath,new ByteArrayInputStream(content.getBytes()));
            ossClient.putObject(putObjectRequest);

            imgUrl = domain + "/" + localUploadFilePath ;

        } catch (Exception e) {
            log.error("上传文件报错，path = {} , e = {}", localUploadFilePath , e);
        }
        return imgUrl;
    }

}
